package managedbeans.livechat;

import entities.Authorisation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import javax.faces.context.FacesContext;
import javax.jms.JMSException;
import javax.naming.NamingException;
import langresources.ResourcesController;

@ManagedBean(name="messageController")
@ApplicationScoped
public class MessageController {

    private int visiblePostsCount = 10;

    public String userMessage;

    public ArrayList<LiveMessage> chatLog = null;

    public MessageController() {
        chatLog = new ArrayList<LiveMessage>();
    }

    private void showMessage(String message){
        FacesMessage fmessage = new FacesMessage(ResourcesController.extractResource("MESSAGE.ACCESS_DENIED"), message);
        FacesContext.getCurrentInstance().addMessage(null, fmessage);
    }

    public void sendMessage(Authorisation user) throws NamingException, JMSException {

         if(user==null){
            showMessage(ResourcesController.extractResource("USER_NOT_AUTHORIZED"));
         } else {

            LiveMessage message = new LiveMessage();
            message.setUsername(user.getUsername());
            message.setDatetime(new Date());
            message.setMessageBody(userMessage);

            chatLog.add(message);

            userMessage="";
         }
    }

    private ArrayList<LiveMessage> trimChatLog(ArrayList<LiveMessage> fullChatLog){
        ArrayList<LiveMessage> trimmedChatLog = new ArrayList<LiveMessage>();
        for(int i=0; i<visiblePostsCount; i++){
            trimmedChatLog.add(fullChatLog.get(i));
        }
        return trimmedChatLog;
    }

    //Getters & Setters

    public ArrayList<LiveMessage> getChatLog() {
        Collections.sort(this.chatLog);
        if(this.chatLog.size() > visiblePostsCount)
            this.chatLog = trimChatLog(this.chatLog);
        return chatLog;
    }

    public void setChatLog(ArrayList<LiveMessage> chatLog) {
         this.chatLog = chatLog;
    }

    public String getUserMessage() {
        return userMessage;
    }

    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

}